package carcassonne.lobby;

import carcassonne.game.player.Player;
import carcassonne.game.player.PlayerInfo;

import java.util.*;
import java.util.function.Predicate;

public class RoomSeat {

    protected PriorityQueue<Player> playerQueue;

    protected final int MaxPlayerCount;

    public RoomSeat(int max) {
        MaxPlayerCount = max;

        playerQueue = new PriorityQueue<>(new Comparator<Player>() {
            @Override
            public int compare(Player player1, Player player2) {
                if (player1.seat == player2.seat) return 0;
                return player1.seat > player2.seat ? 1 : -1;
            }
        });
    }

    public Player GetPlayer(int index) {
        for (Player p : playerQueue) {
            if (p.seat == index) return p;
        }
        return null;
    }

    public void Check(Player player) {
        for (Player p : playerQueue) {
            if (p == player) {
                playerQueue.remove(p);
                break;
            }
        }
    }

    public void AddPlayer(Player player) {
        Check(player);
        playerQueue.add(player);
    }

    public void RemovePlayer(Player player) {
        playerQueue.remove(player);
    }

    public void RemovePlayer(Predicate<? super Player> filter) {
        playerQueue.removeIf(filter);
    }

    public List<Player> GetPlayers() {
        return new ArrayList<>(playerQueue);
    }

    public List<PlayerInfo> GetPlayerInfos() {
        List<PlayerInfo> playerInfos = new ArrayList<>();
        for (Player player : playerQueue) {
            playerInfos.add(player.GetPlayerInfo());
        }
        return playerInfos;
    }

    public int FindSpace() {
        int space = 0;
        for (Player player : playerQueue) {
            if (space >= MaxPlayerCount) return -1;
            if (player.seat > space) return space;
            space++;
        }
        return space >= MaxPlayerCount ? -1 : space;
    }

    public boolean Match(Player player, int index) {
        for (Player p : playerQueue) {
            if (p == player) return p.seat == index;
        }
        return false;
    }

    public boolean isFull(int index) {
        for (Player p : playerQueue) {
            if (p.seat == index) return true;
        }
        return false;
    }

    public void Clear() {
        playerQueue.clear();
    }
}
